package org.example.service;

import okhttp3.*;
import okio.ByteString;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class WSUtil {
    public final OkHttpClient Client;

    public  WebSocket webSocket;

    public  ScheduledExecutorService scheduledExecutorService;

    public WSUtil(String url) {
        Client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30,TimeUnit.SECONDS)
                .build();

        start(url);
    }

    public void start(String url){
        Request request = new Request.Builder()
                .url(url)
                .build();

        webSocket = Client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
                System.out.println("关闭连接reason:"+reason);
                super.onClosed(webSocket, code, reason);
            }

            @Override
            public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
                System.out.println("正在关闭连接reason:"+reason);
                super.onClosing(webSocket, code, reason);
            }

            @Override
            public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
                System.out.println("连接错误response:"+response);
                super.onFailure(webSocket, t, response);
            }

            @Override
            public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
                System.out.println("响应信息text:"+text);
                super.onMessage(webSocket, text);
            }

            @Override
            public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) {
                System.out.println("响应信息bytes:"+bytes);
                super.onMessage(webSocket, bytes);
            }

            @Override
            public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
                System.out.println("开启连接response："+response);
                super.onOpen(webSocket, response);
            }
        });
    }

    public void send(String request){
//        System.out.println("发送请求："+request);
        webSocket.send(request);
    }

    public void close(){
        webSocket.close(1000,"用户主动退出");
    }
}
